package com.cares.fw.coderesource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.cares.fw.database.dao.QueryDAO;
import com.cares.fw.springframework.utils.SpringUtils;

public class DefaultCodeManager implements CodeManager {

	Map<String, List<CodeValue>> cacheMap;
	
	public List<CodeValue> getCodeValueList(String codeId) {
		assert (codeId != null);
		if (cacheMap == null) {
			load();
		}
		
		List<CodeValue> codeList = cacheMap.get(codeId);
		if (codeList == null || codeList.isEmpty()) {
			throw new RuntimeException("no resource found.[id=" + codeId + "]");
		}
		
		return codeList;
	}

	public CodeValue getCodeValue(String codeId, String codeNo) {
		assert (codeId != null);
		assert (codeNo != null);
		
		List<CodeValue> codeList = getCodeValueList(codeId);
		
		for (CodeValue codeValue : codeList) {
			if (codeNo.equals(codeValue.getCodeNo())) {
				return codeValue;
			}
		}
		
		throw new RuntimeException("no resource found.[id=" + codeId + ", no=" + codeNo + "]");
	}
	
	/**
	 * load resource
	 */
	public void load() {
		QueryDAO queryDAO = SpringUtils.getBean(QueryDAO.class);
		List<CodeValue> codeValueList = queryDAO.executeForObjectList("CODE.selectAllDatas", null);
		Map<String, List<CodeValue>> cacheMap = new ConcurrentHashMap<String, List<CodeValue>>();
		for (CodeValue codeValue : codeValueList) {
			List<CodeValue> list = cacheMap.get(codeValue.getCodeId());
			if (list == null) {
				list = new ArrayList<CodeValue>();
				cacheMap.put(codeValue.getCodeId(), list);
			}
			list.add(codeValue);
		}
		
		this.cacheMap = cacheMap;
	}
}
